package chpt12;

/**
 * 测试事务处理2 Batch方式
 *
 */
import java.sql.*;
import java.util.Random;
public class TransactionTest2 {
	public static void main(String[] args) {
		String url = "jdbc:mysql://127.0.0.1:3306/demoDB?serverTimezone=Asia/Chongqing";
		String userName = "root";
		String pwd = "root123";
		String sql = "insert into students(sno, name, gpa) "
				+ "values(?, '陈某', ?)";
		try(Connection con = DriverManager.
				getConnection(url, userName, pwd);) {
			con.setAutoCommit(false);
			int sqlNum = 6;
			Random rd = new Random();
			try(PreparedStatement stmt = con.prepareStatement(sql);){
				for (int i = 1; i <= sqlNum; i++) {
					stmt.setString(1, "JS-"+i);
					double gpa = rd.nextDouble()*4;
					stmt.setDouble(2, gpa);
					stmt.addBatch();
				}
				stmt.executeBatch();
				con.commit();
			}catch (SQLException e) {
				e.printStackTrace();
				try {
					con.rollback();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
		}catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
